<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input v-model="listQuery.name" placeholder="名字" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
            <el-select v-model="listQuery.appId" class="filter-item" clearable placeholder="所属应用">
                <el-option v-for="item in appList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-select v-model="listQuery.company" class="filter-item" clearable placeholder="所属商户">
                <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                查询
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
                新增
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
                关联商品
            </el-button>
        </div>

        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          @sort-change="sortChange"
        >

            <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
                <template slot-scope="{row}">
                    <span>{{ row.id }}</span>
                </template>
            </el-table-column>
            <el-table-column label="名称" width="200px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.name }}</span>
                </template>
            </el-table-column>
            <el-table-column label="品牌logo" width="200px" align="center">
                <template slot-scope="{row}">
                    <img :src="row.logo" style="width: 50px;height:50px;"/>
                </template>
            </el-table-column>
            <el-table-column label="专区大图" width="200px" align="center">
                <template slot-scope="{row}">
                    <img :src="row.bigPic" style="width: 100px;height:60px;"/>
                </template>
            </el-table-column>
            <el-table-column label="品牌故事" width="200px" align="center">
                <template slot-scope="{row}">
                  <el-tooltip class="item" effect="light" :content="row.brandStory" placement="top">
                    <span>{{ row.brandStory.length > 15 ? (row.brandStory.substring(0,15) + '...') : row.brandStory }}</span>
                  </el-tooltip>
                </template>
            </el-table-column>

            <el-table-column label="删除状态" width="200px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.deleteStatus | deleteStatusFilter }}</span>
                </template>
            </el-table-column>

            <el-table-column label="所属商户" width="200px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.companyName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="所属应用" width="200px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.appName }}</span>
                </template>
            </el-table-column>
          <el-table-column label="产品数量" width="100px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.productCount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="评论数量" width="100px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.productCommentCount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="排序" width="80px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.orderNum }}</span>
            </template>
          </el-table-column>
          <el-table-column label="品牌制造商" width="160px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.factoryStatus == 1 ? '是' : '不是' }}</span>
            </template>
          </el-table-column>
            <el-table-column label="创建时间" width="200px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.createTime }}</span>
                </template>
            </el-table-column>
            <el-table-column label="更新时间" width="200px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.updateTime }}</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width" fixed="right">
                <template slot-scope="{row,$index}">
                    <el-button type="primary" size="mini" @click="handleUpdate(row)">
                        编辑
                    </el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
          <el-row>
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="margin:0 50px;">
              <el-col :span="11" style="margin: 0 50px 0 0">
                <el-form-item label="名称">
                  <el-input v-model="temp.name"/>
                </el-form-item>
                <el-form-item label="品牌logo">
                  <single-upload v-model="temp.logo" />
                </el-form-item>
                <el-form-item label="专区大图">
                  <single-upload v-model="temp.bigPic" />
                </el-form-item>
                <el-form-item label="品牌故事">
                  <el-input v-model="temp.brandStory" type="textarea" rows="3"/>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="商户" prop="company">
                  <el-select v-model="temp.company" class="filter-item" clearable placeholder="请选择">
                    <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="应用">
                  <el-select v-model="temp.appId" class="filter-item" clearable placeholder="请选择">
                    <el-option v-for="item in appList" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="产品数量">
                  <el-input v-model="temp.productCount" />
                </el-form-item>
                <el-form-item label="产品评论数量">
                  <el-input v-model="temp.productCommentCount" />
                </el-form-item>
                <el-form-item label="排序">
                  <el-input v-model="temp.orderNum" />
                </el-form-item>
                <el-form-item label="品牌制造商">
                  <el-radio-group ref="roleGroup" v-model="temp.factoryStatus" style="padding: 5px 15px;">
                    <el-radio v-for="item in factoryStatusList" :label="item.id" style="width: 90px;">
                      {{ item.name }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>


            </el-form>
          </el-row>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                    取消
                </el-button>
                <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
                    确定
                </el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import {
        brandList,
        brandCreate,
        brandUpdate,
        brandDelete
    } from '@/api/brand'
    import {companyList, userAppList} from '@/api/sys'
    import waves from '@/directive/waves' // waves directive
    import Pagination from '@/components/Pagination' // secondary package based on el-pagination

    import SingleUpload from '@/components/Upload/singleUpload'
    import MultiUpload from '@/components/Upload/multiUpload'

    const defaultListQuery = {
        page: 1,
        limit: 15,
        name: '',
        company: '',
        appId:'',
        sort: '+id'
    };

    const currentTemp = {
        id: undefined,
        name: undefined,
        orderNum: undefined,
        factoryStatus: undefined,
        productCount: undefined,
        productCommentCount: undefined,
        logo: undefined,
        bigPic: undefined,
        brandStory: undefined,
        deleteStatus: undefined,
        company: undefined,
        appId: undefined,
        createTime: undefined,
        updateTime: undefined,
    }

    export default {
        name: 'brand',
        components: { Pagination, SingleUpload, MultiUpload },
        directives: { waves },
        data() {
            // var name = (rule, value, callback) => {
            //   if (value === '') {
            //     callback(new Error('模拟后台校验，请输入用户名'));
            //   } else {
            //     callback();
            //   }
            // }
            return {
                tableKey: 0,
                list: null,
                total: 0,
                listLoading: true,
                listQuery: Object.assign({}, defaultListQuery),
                temp: Object.assign({}, currentTemp),
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '修改',
                    create: '新增'
                },
                rules: {
                    // name: [{ validator: name, trigger: 'blur' }]
                },
                companyList: [],
                appList: [],
                factoryStatusList:[{id:0,name:'不是'},{id:1,name:'是'}]
            }
        },
        created() {
            this.getList()

            this.appListFun()

            this.companyListFun()
        },
        filters: {
          deleteStatusFilter(value) {
            if (value === 1) {
              return '已删除';
            } else {
              return '未删除';
            }
          }
        },
        methods: {
            getList() {
                this.listLoading = true
                brandList(this.listQuery).then(response => {
                    this.list = response.data.content
                    this.total = parseInt(response.data.totalElements)

                    this.listLoading = false
                })
            },
            handleFilter() {
                this.listQuery.page = 1
                this.getList()
            },
            sortChange(data) {
                const { prop, order } = data
                if (prop === 'id') {
                    this.sortByID(order)
                }
            },
            sortByID(order) {
                if (order === 'ascending') {
                    this.listQuery.sort = '+id'
                } else {
                    this.listQuery.sort = '-id'
                }
                this.handleFilter()
            },
            resetTemp() {
                this.temp = Object.assign({}, currentTemp)
            },
            async appListFun(){
                await userAppList({id: -1}).then(response => {
                    this.appList = response.data.apps;
                })
            },
            async companyListFun(){
                this.companyList = []
                await companyList({page: 1, limit: 10000, sort: '+id'}).then(response => {
                    this.companyList = response.data.content
                    // this.companyList.unshift({id: '0', name: '无'})
                })
            },
            handleCreate() {
                this.resetTemp()
                this.appListFun()
                this.companyListFun()

                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })

            },
            createData() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        brandCreate(this.temp).then(() => {
                            this.list.unshift(this.temp)
                            this.dialogFormVisible = false
                            this.$notify({
                                title: '提示',
                                message: '操作成功',
                                type: 'success',
                                duration: 2000
                            })
                            this.getList()
                        })
                    }
                })
            },
            handleUpdate(row) {
                this.appListFun()
                this.companyListFun()

                this.temp = Object.assign({}, row) // copy obj
                this.dialogStatus = 'update'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })

            },
            updateData() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        const tempData = Object.assign({}, this.temp)
                        tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
                        brandUpdate(tempData).then(() => {
                            const index = this.list.findIndex(v => v.id === this.temp.id)
                            this.list.splice(index, 1, this.temp)
                            this.dialogFormVisible = false
                            this.$notify({
                                title: '提示',
                                message: '操作成功',
                                type: 'success',
                                duration: 2000
                            })
                            this.getList()
                        })
                    }
                })
            },
            handleDelete(row, index) {
                const tempData = {};
                tempData.id = row.id;
                const that = this;
                this.$confirm('确认删除？', '系统提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    cancelButtonClass: 'btn-custom-cancel',
                    type: 'warning'
                }).then(function(){
                    brandDelete(tempData).then(() => {
                        that.$notify({
                            title: '提示',
                            message: '操作成功',
                            type: 'success',
                            duration: 2000
                        })
                        that.getList()
                    })
                }).catch(function(){
                    // console.log("取消成功！");
                })
            }
        }
    }
</script>

<style lang="scss" scoped>
  .el-tooltip__popper.is-light {
    background: #e8f4ff !important;
    border: 1px solid #c1c7d2 !important;
  }

</style>
